import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

public class Solution1368 {
    public int minCost(int[][] grid) {
        Queue<int[]> queue=new LinkedList<>();
        int[][] visit=new int[grid.length][grid[0].length];
        for (int i=0;i<grid.length;i++){
            Arrays.fill(visit[i],Integer.MAX_VALUE);
        }
        visit[0][0]=0;
        queue.offer(new int[]{0,0});
        int[] dx={-1,0,0,1,-1};
        int[] dy={-1,1,-1,0,0};
        while (!queue.isEmpty()){
            int[] t=queue.poll();
            for (int i=1;i<=4;i++){
                int m=visit[t[0]][t[1]]+(i==grid[t[0]][t[1]]?0:1);
                int x=t[0]+dx[i];
                int y=t[1]+dy[i];
                if (x>=0 && x<grid.length && y>=0 && y<grid[0].length && visit[x][y]>m){
                    visit[x][y]=m;
                    queue.offer(new int[]{x,y});
                }
            }
        }
        return visit[grid.length-1][grid[0].length-1];
    }

    public static void main(String[] args) {
        System.out.println(new Solution1368().minCost(new int[][]{{1,1,3},{3,2,2},{1,1,4}}));
    }
}
